import React, { useState, useEffect, useRef, Fragment } from 'react'
import { Picker, Button, Toast } from 'antd-mobile'
import idcard from 'idcard'
import { withRouter } from 'react-router-dom'
import SelectPhoneNumber from './SelectPhoneNumber'
import CheckInformation from './CheckInformation'
import IdcardUploadMessage from './IdcardUploadMessage'
import { getProvinceWithCity, getCityWithArea } from './address'
import { checkIsFull16, checkName } from '../../util'
import {
  getCardClass,
  sendMsg,
  checkVerifyCode,
  getNumberAddress,
  getToken
} from '../../request/home'
import Agreement from './Agreement'
import ErrorMessage from './ErrorMessage'
import HelpPlaceOrder from './HelpPlaceOrder'
import './style.scss'

Toast.config({ duration: 2, mask: false })

function Home(props) {
  const [formData, setFormData] = useState({
    page_name: '',
    true_name: '',
    idcard: '',
    phone: '',
    new_phone: '',
    address: '',
    url_query_string: window.location.search.replace('?', '')
  })
  const [verifyCode, setVerifyCode] = useState('')
  const [isShowSelectNumber, setIsShowSelectNumber] = useState(false)
  const [isShowCheckInformation, setIsShowCheckInformation] = useState(false)
  const [lastSecond, setLastSecond] = useState(0)
  const [verifyUuid, setVerifyUuid] = useState('')
  const [provinceList, setProvinceList] = useState([])
  const [cityList, setCityList] = useState([])
  const [cardAddress, setCardAddress] = useState([])
  const [cardAddressText, setCardAddressText] = useState([])
  const [expressAddress, setExpressAddress] = useState([])
  const [expressAddressText, setExpressAddressText] = useState([])
  const [token, setToken] = useState('')
  const [isCheckAgreement, setIsCheckAgreement] = useState(true)
  const [isShowAgreement, setIsShowAgreement] = useState(false)
  const [idcardUploadUrl, setIdcardUploadUrl] = useState(false)
  const [isShowHelpPlaceOrder, setIsShowHelpPlaceOrder] = useState(false)
  const [errorMsg, setErrorMsg] = useState('')
  const [orderNo, setOrderNo] = useState('')
  const [cardClass, setCardClass] = useState({
    code: '',
    name: '',
    head_img_url: '',
    tail_img_url: '',
    sms_flag: 0,
    url_param: '',
    icp_flag: 0,
    icp: []
  })
  const topImgRef = useRef(null)
  const addressRef = useRef([])
  const containerRef = useRef(null)
  const copyrightRef = useRef(null)

  useEffect(() => {
    const searchParams = new URLSearchParams(window.location.search)
    const productCode = searchParams.get('code')
    getCardClassDetail(productCode).catch(e => console.log(e.message))
    getAddress().catch(e => console.log(e.message))
  }, [])

  useEffect(() => {
    if (lastSecond > 0) {
      setTimeout(() => setLastSecond(lastSecond - 1), 1000)
    }
  }, [lastSecond])

  useEffect(() => {
    setFormData({ ...formData, new_phone: '' })
    if (cardAddress.length !== 2) {
      return
    }
    const province = addressRef.current.find(item => item.provinceId === cardAddress[0])
    if (!province) {
      return
    }
    setCityList(getCityWithArea(province.cityList))
    const city = province.cityList.find(item => item.cityId === cardAddress[1])
    if (city) {
      setCardAddressText([province.provinceName, city.cityName])
    }
  }, [cardAddress])

  useEffect(() => {
    if (expressAddress.length !== 2) {
      return
    }
    const city = cityList.find(item => item.value === expressAddress[0])
    if (!city) {
      return
    }
    const area = city.children.find(item => item.value === expressAddress[1])
    if (area) {
      setExpressAddressText([city.label, area.label])
    }
  }, [expressAddress])

  const getCardClassDetail = async(productCode) => {
    const { code, data } = await getCardClass({ code: productCode })
    if (code) {
      props.history.push('/error')
      return false
    }
    const icpArr = (data.icp || '').split('\n')
    if (icpArr.length === 1 && !icpArr[0].trim()) {
      icpArr.pop()
    }
    setCardClass({ ...data, icp: icpArr })
    document.title = data.page_name || ''
    containerRef.current.style.backgroundColor = data.bg_color || '#202342'
    if (copyrightRef.current) {
      copyrightRef.current.style.backgroundColor = data.bg_color || '#202342'
    }
  }

  const getCode = async() => {
    if (lastSecond > 0) {
      return false
    }
    if (!formData.phone.trim()) {
      Toast.info('联系电话不能为空')
      return false
    }
    const { code, message, data } = await sendMsg({ phone: formData.phone })
    if (code) {
      Toast.fail(message)
      return false
    }
    setVerifyUuid(data.verify_uuid)
    setLastSecond(60)
  }

  const getAddress = async() => {
    const { code, data } = await getNumberAddress()
    if (code) {
      Toast.fail('获取地址失败，请稍后重试')
      return false
    }
    addressRef.current = data
    const province = getProvinceWithCity(data)
    setProvinceList(province)
  }

  const getApplyToken = async() => {
    const searchParams = new URLSearchParams(window.location.search)
    const productCode = searchParams.get('code')
    const { code, data } = await getToken(productCode)
    if (code) {
      Toast.fail('获取token失败，请稍后再试')
      return false
    }
    setToken(data.token)
  }

  const onSelectNumber = () => {
    if (!cardAddress.length) {
      Toast.info('请选择号码归属地')
      return false
    }
    setIsShowSelectNumber(true)
  }

  const onSubmit = async() => {
    if (!formData.true_name) {
      Toast.info('请输入申办人姓名')
      return false
    }
    if (!checkName(formData.true_name)) {
      return Toast.info('请输入正确的姓名')
    }
    if (!formData.idcard) {
      Toast.info('请输入申办人身份证号码')
      return false
    }
    if (!idcard.verify(formData.idcard)) {
      Toast.info('请输入正确的身份证号码')
      return false
    }
    if (!checkIsFull16(formData.idcard)) {
      return Toast.info('未满16周岁暂时无法申请')
    }
    if (!formData.phone) {
      Toast.info('请输入联系电话')
      return false
    }
    if (!(/^1[3456789]\d{9}$/.test(formData.phone))) {
      Toast.info('联系电话格式有误，请重新输入')
      return false
    }
    if (!formData.new_phone) {
      Toast.info('请选择号码')
      return false
    }
    if (!expressAddress.length) {
      Toast.info('请选择配送地区')
      return false
    }
    if (!formData.address) {
      Toast.info('请填写详细地址')
      return false
    }
    if (cardClass.sms_flag) {
      if (!verifyCode) {
        Toast.info('验证码不能为空')
        return false
      }
      const { code } = checkVerifyCode({
        verify_uuid: verifyUuid,
        phone: formData.phone,
        verify_code: verifyCode
      })
      if (code) {
        Toast.info('验证码校验失败')
        return false
      }
    }

    setIsShowCheckInformation(true)
  }

  return (
    <div className="home">
      <div className="img-wrapper" ref={topImgRef}>
        {cardClass.head_img_url && (
          <img
            src={cardClass.head_img_url}
            onClick={() => {
              window.scrollTo({ top: topImgRef.current.clientHeight, behavior: 'smooth' })
            }}
          />
        )}
      </div>
      <div className="container" ref={containerRef}>
        <div className="content">
          <div className="title">
            <img src={require('../../assets/images/title.png')} alt="信息填写"/>
          </div>
          <div className="apply-form">
            <div className="apply-form-item">
              <div className="label">
                <img src={require('../../assets/images/xingming.png')} alt=""/>
              </div>
              <input
                type="text"
                placeholder="请输入申办人姓名"
                onChange={e => setFormData({ ...formData, true_name: e.target.value.trim() })}
              />
            </div>
            {(formData.true_name.length > 1 || cardClass.idcard_display === 1) && (
              <div className="apply-form-item">
                <div className="label">
                  <img src={require('../../assets/images/xingming.png')} alt=""/>
                </div>
                <input
                  type="text"
                  placeholder="请输入申办人身份证号码"
                  onChange={e => setFormData({ ...formData, idcard: e.target.value.trim() })}
                />
              </div>
            )}
            <div className="apply-form-item">
              <div className="label">
                <img src={require('../../assets/images/phone.png')} alt=""/>
              </div>
              <input
                type="number"
                placeholder="联系电话"
                onChange={e => setFormData({ ...formData, phone: e.target.value })}
              />
            </div>
            {!!cardClass.sms_flag && (
              <div className="apply-form-item code">
                <div className="label">
                  <img src={require('../../assets/images/code.png')}/>
                </div>
                <input
                  type="number"
                  placeholder="输入验证码"
                  onChange={e => setVerifyCode(e.target.value)}
                />
                <span onClick={getCode}>
                  {lastSecond > 0 ? `${lastSecond}秒后重新获取` : '获取验证码'}
                </span>
              </div>
            )}
            <p className="apply-form-title">请选择号码</p>
            {provinceList.length > 0 && (
              <Picker
                title="号码归属"
                data={provinceList}
                cols={2}
                value={cardAddress}
                onOk={value => {
                  setCardAddress(value)
                  setExpressAddress([value[1], ''])
                }}
              >
                <div className="apply-form-item">
                  <div
                    className={cardAddressText.length ? 'area-select-label area-selected' : 'area-select-label'}
                  >
                    {cardAddressText.join('/') || '请选择号码归属'}
                  </div>
                </div>
              </Picker>
            )}
            <div className="apply-form-item" onClick={onSelectNumber}>
              <div className={formData.new_phone ? 'area-select-label area-selected' : 'area-select-label'}>
                {formData.new_phone || '请选择号码'}
              </div>
            </div>
            <p className="apply-form-title">请填写配送地址<span>(仅限省内配送)</span></p>
            {cardAddress.length > 0 ? (
              <Picker
                title="选择地区"
                data={cityList}
                cols={2}
                value={expressAddress}
                onOk={value => setExpressAddress(value)}
              >
                <div className="apply-form-item">
                  <div
                    className={expressAddressText.length > 0 && !!expressAddress[1] ? 'area-select-label area-selected' : 'area-select-label'}
                  >
                    {expressAddress.length > 0 && !!expressAddress[1] ? cardAddressText[0] + '/' + expressAddressText.join('/') : '请选择地区'}
                  </div>
                </div>
              </Picker>
            ) : (
              <div className="apply-form-item" onClick={() => Toast.info('请选择号码归属地', 2)}>
                <div className="area-select-label">请选择地区</div>
              </div>
            )}
            <div className="apply-form-item">
              <input
                className="address"
                type="text"
                placeholder="村/小区/写字楼+门牌号"
                onChange={e => setFormData({ ...formData, address: e.target.value.trim() })}
                onBlur={() => {
                  window.scrollTo({ top: topImgRef.current.clientHeight, behavior: 'smooth' })
                }}
              />
            </div>
            <p className="agreement">
              <input
                type="checkbox"
                checked={isCheckAgreement}
                onChange={e => setIsCheckAgreement(e.target.checked)}
              />
              &nbsp;我已阅读并同意
              <span onClick={() => {
                if (!cardAddress.length) {
                  Toast.info('请选择号码归属地')
                } else {
                  setIsShowAgreement(true)
                }
              }}>
                《中国移动用户入网协议》
              </span>
            </p>
            <Button disabled={!isCheckAgreement} type="warning" onClick={onSubmit}>立即提交，免费送货上门</Button>
          </div>
        </div>
      </div>
      <div className="img-wrapper">
        {cardClass.tail_img_url && (
          <img
            src={cardClass.tail_img_url}
            onClick={() => {
              window.scrollTo({ top: topImgRef.current.clientHeight, behavior: 'smooth' })
            }}
          />
        )}
      </div>
      {cardClass.icp_flag === 1 && (
        <div className="copyright" ref={copyrightRef}>
          {cardClass.icp.length ? (
            cardClass.icp.map((item, index) => (
              <p key={index}>{item}</p>
            ))
          ) : (
            <Fragment>
              <p>浙江联发创新电子科技有限公司</p>
              <p>提供安全、快捷、低价的手机号卡、话费、流量等业务</p>
              <p>联系电话：0574-88301000</p>
              <p>地址：浙江省宁波市鄞州区首南街道联安文体大厦</p>
              <p>浙ICP备17017272号-1</p>
            </Fragment>
          )}
        </div>
      )}
      {isShowSelectNumber && (
        <SelectPhoneNumber
          visible={isShowSelectNumber}
          token={token}
          addressCode={cardAddress}
          addressText={cardAddressText}
          getToken={() => getApplyToken()}
          selectNumber={number => setFormData({ ...formData, new_phone: number })}
          close={() => setIsShowSelectNumber(false)}
        />
      )}
      {isShowCheckInformation && token && (
        <CheckInformation
          visible={isShowCheckInformation}
          token={token}
          formData={{ ...formData, ...cardClass, cardAddress, cardAddressText, expressAddress, expressAddressText }}
          close={() => setIsShowCheckInformation(false)}
          setErrorMessage={msg => setErrorMsg(msg)}
          setOrderNo={orderNo => setOrderNo(orderNo)}
          setIdcardUploadUrl={url => setIdcardUploadUrl(url)}
          showHelpOrder={() => setIsShowHelpPlaceOrder(true)}
        />
      )}
      {isShowAgreement && (
        <Agreement
          visible={isShowAgreement}
          cardAddress={cardAddress}
          close={() => setIsShowAgreement(false)}
        />
      )}
      {!!errorMsg && (
        <ErrorMessage
          content={errorMsg}
          orderNo={orderNo}
          close={() => {
            setErrorMsg('')
            setOrderNo('')
          }}
        />
      )}
      {!!idcardUploadUrl && (
        <IdcardUploadMessage url={idcardUploadUrl} close={() => setIdcardUploadUrl(null)}/>
      )}
      {!!isShowHelpPlaceOrder && orderNo && (
        <HelpPlaceOrder
          visible={isShowHelpPlaceOrder}
          close={() => setIsShowHelpPlaceOrder(false)}
          orderNo={orderNo}
        />
      )}
    </div>
  )
}

export default withRouter(Home)
